package com.learning.spring.data.orm.dao.design.dao;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * ClassName: BaseDao
 * Description: 基础的 DAO
 * Date: 2020/11/4 19:50 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Transactional(rollbackFor = Exception.class)
public class BaseDao<T> {

    @Autowired
    private SqlSessionTemplate sessionTemplate;

    private Class<T> clazz;

    /**
     * 构造函数，反射获取泛型
     */
    public BaseDao() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] params = ((ParameterizedType) type).getActualTypeArguments();
            clazz = (Class<T>) params[0];
        }
    }

    @Transactional(rollbackFor = Exception.class, readOnly = true)
    public T get(Serializable id) {
        return sessionTemplate.selectOne("", id);
    }

    public int save() {
        return sessionTemplate.insert("");
    }

}
